package com.ht.web360.base.utils;


import com.ht.web360.base.dto.UserInfo.dto.UserInfoDto;
import com.ht.web360.base.utils.exceptions.MessageException;

public class ThreadLocalUtil {
    static final ThreadLocal<Long> userIdTL = new ThreadLocal<>();
    static final ThreadLocal<UserInfoDto> userTL = new ThreadLocal<>();

    public static void setUserId(long uid) {
        userIdTL.set(uid);
    }

    public static Long getUserId() {
        Long l = userIdTL.get();
        if (l == null) {
            throw new MessageException("用户id为空");
        }
        return l;
    }

    /**
     * 清理所有ThreadLocal数据，防止线程池窜数据
     */
    public static void removeAll() {
        userTL.remove();
    }

    public static void setUserDto(UserInfoDto userInfoDto) {
        userTL.set(userInfoDto);
    }

    public static UserInfoDto getUserDto() {
        UserInfoDto dto = userTL.get();
        if (dto == null) {
            throw new RuntimeException("无法读取用户信息，检查控制器方法的用户权限");
        }
        return dto;
    }
}